<template>
  <div class="main-content no-padding">
    <div class="container-fluid">
      <div class="panel">
        <div class="panel-body">
          <el-row>
            <el-col :span="10" :offset="7">
              <el-input placeholder="编码或名称" v-model="searchText" class="input-with-select">
                <template #append>
                  <el-button icon="el-icon-search" @click="search"></el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="7">
              <el-button class="pull-right" @click="dialogAddVisible=true">添加参数</el-button>
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="panel">
        <el-table
          :data="tableData"
          stripe
          style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <el-tag v-for="(expression, index) in props.row.expressions"
                      :type="expression.type === 1? 'danger' : 'success'" :key="index">{{ expression.symbol }}
              </el-tag>
              <pre>
                {{ props.row.data }}
              </pre>
            </template>
          </el-table-column>
          <el-table-column
            width="50px"
            label="ID"
            prop="id">
          </el-table-column>
          <el-table-column
            width="200"
            label="名称"
            prop="name">
          </el-table-column>
          <el-table-column
            width="120"
            label="参数基本类型"
            prop="parameterType">
          </el-table-column>
          <el-table-column
            width="120"
            label="示例值"
            prop="example">
          </el-table-column>
          <el-table-column
            width="120"
            label="默认值"
            prop="defaultValue">
          </el-table-column>
          <el-table-column
            width="120"
            :formatter="formatterType"
            label="参数类型"
            prop="type">
          </el-table-column>
          <el-table-column
            label="fetcher"
            prop="fetcher">
          </el-table-column>
          <el-table-column
            label="converter"
            prop="converter">
          </el-table-column>
          <el-table-column
            label="描述"
            prop="description">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template #default="scope">
              <el-button type="text" size="small">编辑</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-model:current-page="page.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          v-model:page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          v-model:total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="添加参数"
      v-model="dialogAddVisible"
      width="50%">
      <el-form label-position="left" label-width="150px" :rules="rules" :model="ruleParam" ref="ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleParam.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="ruleParam.description"></el-input>
        </el-form-item>
        <el-form-item label="参数基本类型" prop="parameterType">
          <el-select v-model="ruleParam.parameterType" placeholder="请选择">
            <el-option label="整数" value="int"></el-option>
            <el-option label="小数" value="double"></el-option>
            <el-option label="字符串" value="string"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="示例值">
          <el-input v-model="ruleParam.example"></el-input>
        </el-form-item>
        <el-form-item label="默认值">
          <el-input v-model="ruleParam.defaultValue"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="ruleParam.type" placeholder="请选择">
            <el-option label="原始参数" :value=1></el-option>
            <!--            <el-option label="衍生参数" :value=2></el-option>-->
          </el-select>
        </el-form-item>
        <el-form-item label="fetcher" v-show="ruleParam.type === 1">
          <el-select v-model="ruleParam.fetcher" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in fetchers"
              :key="item.id"
              :label="item.name"
              :value="item.name">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.description }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="fetcher变量名称" v-show="ruleParam.type===1">
          <el-input v-model="ruleParam.paramAlias"></el-input>
        </el-form-item>
        <el-form-item label="转换器配置" v-show="ruleParam.type===1">
          <el-radio-group v-model="ruleParam.hasConverter" size="medium">
            <el-radio border :label="1">无</el-radio>
            <el-radio border :label="2">配置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="转换器(converter)" v-show="ruleParam.hasConverter === 2">
          <el-input v-model="ruleParam.converter"></el-input>
        </el-form-item>

        <!--        衍生参数逻辑开始 -->
        <el-form-item label="计算表达式配置" v-show="ruleParam.type === 2">
          <el-tag v-for="(expression, index) in ruleParam.expressions"
                  :type="expression.type === 1? 'danger' : 'success'" :key="index">{{ expression.symbol }}
          </el-tag>
          <el-button type="primary" icon="el-icon-plus" size="small" style="margin-left: 10px"
                     @click="showAndMixOptionsSymbols">添加表达式
          </el-button>
        </el-form-item>
        <!--        衍生参数逻辑结束 -->

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRulesParam">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="添加表达式"
      v-model="dialogAddExpressionVisible"
      width="300px">
      <el-form label-position="left" label-width="50px">
        <el-form-item label="类型">
          <el-select v-model="symbol" placeholder="请选择">
            <el-option :label="sym" :value="sym" v-for="(sym, index) in optionalSymbols" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddExpressionVisible = false">取 消</el-button>
          <el-button type="primary" @click="appendExpression">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import {ElMessage} from 'element-plus'
import {addRulesParam, fetchRuleCalcParamConfig} from '@/api/engine/rulesParamConfig'
import {fetchFetcherConfig} from '@/api/engine/fetcherConfig'


export default {
  name: "BaseRulesParamConfig",
  data() {
    return {
      fetchers: [],
      dialogAddVisible: false,
      dialogAddExpressionVisible: false,
      lastType: 0,  // 0 初始化开始; 1: 计算参数; 2: 运算符;
      lastSymbol: '',
      lastCalcParamType: 0,
      symbol: '',
      optionalSymbols: [],
      ruleParam: {
        example: "",
        defaultValue: "",
        hasConverter: 1,
        name: "",
        paramAlias: "",
        type: 1,
        parameterType: "",
        fetcher: "",
        converter: "",
        expressionSymbols: "",
        description: "",
        expressions: [],
      },
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      searchText: '',
      tableData: [],
      rules: {
        name: [
          {required: true, message: '请输入参数名称', trigger: 'blur'},
          {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入描述信息', trigger: 'blur'},
          {min: 3, max: 120, message: '长度在 3 到 120 个字符', trigger: 'blur'}
        ],
        parameterType: [
          {required: true, message: '请选择参数基本类型', trigger: 'change'}
        ]
      }
    };
  },
  methods: {
    showAndMixOptionsSymbols() {
      let that = this
      that.dialogAddExpressionVisible = true
      that.optionalSymbols = []
      that.symbol = ''
      if (that.lastType === 0) {
        // 初始化开始
        fetchRuleCalcParamConfig(1, 1_000_000).then(response => {
          that.optionalSymbols = response.data.dataList.map(item => {
            return item.name
          })
        })
      } else if (that.lastType === 1) {
        // 添加运算符
        // 获取上一个参数的类型
        that.optionalSymbols = ['+', '-', '*', '/']
      } else {
        // 添加计算参数
        fetchRuleCalcParamConfig(1, 1_000_000).then(response => {
          that.optionalSymbols = response.data.dataList.map(item => {
            return item.name
          })
        })
      }
    },
    appendExpression() {
      let symbol = this.symbol
      this.lastSymbol = symbol

      this.lastType = this.lastType === 1 ? 2 : 1

      this.ruleParam.expressions.push({
        symbol: symbol,
        type: this.lastType
      });

      this.dialogAddExpressionVisible = false

    },
    handleSizeChange() {
      this.search()
    },
    handleCurrentChange() {
      this.search()
    },
    formatterType(row) {
      return row.type === 1 ? "原始参数" : "衍生参数"
    },

    addRulesParam() {
      let that = this

      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 验证通过了
          if (that.ruleParam.type === 1) {

            // 原始参数
            if (that.ruleParam.fetcher === null || that.ruleParam.fetcher.trim().length === 0) {
              ElMessage.error('请输入 mapper');
              return false;
            }

            if (that.ruleParam.hasConverter === 2) {
              // 有转换器
              if (that.ruleParam.converter === null || that.ruleParam.converter.trim().length === 0) {
                ElMessage.error('请输入 converter');
                return false;
              }
            } else {
              that.ruleParam.converter = "";
            }
            that.ruleParam.expressionSymbols = "";
          } else {
            if (that.ruleParam.expressions.length === 0 || that.ruleParam.expressions.length % 2 !== 1) {
              ElMessage.error('请输入计算表达式配置');
              return false;
            }
            that.ruleParam.expressionSymbols = JSON.stringify(that.ruleParam.expressions)
            that.ruleParam.fetcher = ""
            that.ruleParam.converter = ""
          }

          addRulesParam(that.ruleParam).then(() => {
            that.dialogAddVisible = false
            that.search()
            that.ruleParam = {
              hasConverter: 1,
              name: "",
              paramAlias: "",
              type: 1,
              parameterType: "",
              fetcher: "",
              converter: "",
              expressionSymbols: "",
              description: "",
              expressions: [],
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    search: function () {
      let that = this
      fetchRuleCalcParamConfig(that.page.currentPage, that.page.pageSize).then(response => {
        that.tableData = response.data.dataList
        that.page.total = response.data.totalCount
        that.tableData.forEach(item => {
          if (item.expressionSymbols)
            item.expressions = JSON.parse(item.expressionSymbols)
        })
      })
    },
    reloadFetchers() {
      let that = this
      fetchFetcherConfig(1, 1_000_000).then(response => {
        that.fetchers = response.data.dataList
      })
    },
  },
  mounted() {
    this.search()
    this.reloadFetchers()
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
